﻿using System.Reflection;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Linq;

namespace DynamicGeometry
{
    public class MethodCallerButton : Button
    {
        public MethodCallerButton()
        {
            this.Click += MethodCallerButton_Click;
            this.Margin = new System.Windows.Thickness(0, 4, 0, 4);
        }

        void MethodCallerButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Target != null && Method != null)
            {
                try
                {
                    object[] arguments = new object[0];
                    if (ParameterGrid != null)
                    {
                        IEnumerable<IValueProvider> parameterValues = ParameterGrid.CurrentProperties;
                        arguments = parameterValues.Select(v => v.GetValue<object>()).ToArray();
                    }
                    Method.Invoke(Target, arguments);
                }
                catch
                {
                    // whatever happens, we can't allow it bubble up
                    // back to the CLR - we don't trust our method
                }
            }
        }

        public object Target { get; set; }
        public PropertyGrid ParameterGrid { get; set; }

        private MethodInfo mMethod;
        public MethodInfo Method
        {
            get
            {
                return mMethod;
            }
            set
            {
                mMethod = value;
                if (mMethod != null)
                {
                    string name = mMethod.Name;
                    var attribute = mMethod.GetAttribute<PropertyGridNameAttribute>();
                    if (attribute != null)
                    {
                        name = attribute.Name;
                    }

                    var parameters = mMethod.GetParameters();
                    if (parameters.Length == 0)
                    {
                        this.Content = name;
                    }
                    else
                    {
                        ParameterGrid = new PropertyGrid(new ParameterDiscoveryStrategy());
                        ParameterGrid.Title = mMethod.Name;
                        this.Content = ParameterGrid;
                        this.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
                        this.VerticalContentAlignment = System.Windows.VerticalAlignment.Stretch;
                        ParameterGrid.Show(mMethod, null);
                    }
                }
            }
        }
    }
}
